import React, { Component } from 'react';
import { StyleSheet, Text, View, TouchableOpacity, Image, ScrollView } from "react-native";
import { GLOBAL } from '../../../config/global';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import { API, API_GENERATE } from '../../../config/api';
import HTTP from '../../../utils/http';
import { style } from '../../../theme/style';
import { Common } from '../../../component/common/Common.js';
import { CommonDialog } from '../../../components/common/Dialog';
import MethodUtil from '../../../utils/MethodUtil'

const scale = GLOBAL.SCALE;

export class AccountDetailPage extends Component {
  static navigationOptions = ({ navigation }) => {
    return {
      headerTitle: '结算单详情',
      headerTintColor: style.color.white,
      headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
      headerRight: (<Image style={style.head.headRightEmpty} source={require('../../../imgs/goBackEmpty.png')} />),
      headerStyle: style.head.headerStyle,
      headerTitleStyle: {
        flex: 1,
        textAlign: 'center',
      }
    }
  };

  constructor(props) {
    super(props)

    this.state = {
      status: 'data',
      modalVisible: false,
      modalTitle: '',
      alertRemark: ''
    }

    this.pageParams = this.props.navigation.state.params || {};
  }

  componentWillMount() {
    this.initPage();
  }

  async initPage() {
    this.setState({
      status: 'loading'
    })
    let res = await HTTP.POST(API_GENERATE(API.GET_SETTLE_DETAIL), {
      invoiceId: this.pageParams.invoiceId,
      companyType: this.pageParams.companyType
    }); // TODO
    this.setState({
      detail: res,
      status: res ? 'data' : 'error',
    })
  }

  // 查看备注/审批意见
  showRemark = (index, alertRemark) => {
    this.setState({
      modalVisible: true,
      modalTitle: index ? '审批意见' : '备注',
      alertRemark
    })
  }

  render() {
    let { status, modalVisible, modalTitle, alertRemark, detail } = this.state;
    // let { settlePurchaseHeadVO, settleSaleHeadVO } = detail || {};
    // let curDetail = this.pageParams.companyType === 1 ? (settlePurchaseHeadVO || {}) : (settleSaleHeadVO || {});
    const { settleId, settleTotQuantity, invoiceAmountIntax, settleTotAmount, discountAmount, diffNoTax, diffTaxAmount,
      settleDate, invocieDate, remark, rejectsRemark, settlePurchaseLineVOs, settleSaleLineVOs, invoiceInfoList } = detail || {};
    const detailItemList = this.pageParams.companyType === 1 ? (settlePurchaseLineVOs || []) : (settleSaleLineVOs || []);
    return (
      <View style={styles.container}>
        {
          detail ?
            <ScrollView style={{ paddingLeft: 12 * scale, paddingRight: 12 * scale }}>
              <View style={styles.accountNum}>
                <Text style={{ fontSize: 15 * scale }}>结算单号：{settleId || '-'}</Text>
                <Text style={{ color: '#E02020', fontWeight: 'bold' }}>结算</Text>
              </View>

              <View style={styles.section}>
                <View style={styles.commonLine}>
                  <Text style={styles.commonLabel}>结算总量（吨）</Text>
                  <Text style={styles.commonLabel}>结算总额（元）</Text>
                  <Text style={styles.commonLabel}>折扣总额（元）</Text>
                </View>
                <View style={styles.commonLine}>
                  <Text style={styles.commonText}>{settleTotQuantity || 0}</Text>
                  <Text style={styles.commonText}>¥{this.pageParams.companyType === 1 ? MethodUtil.toThousands(invoiceAmountIntax, 2) : MethodUtil.toThousands(settleTotAmount, 2) || 0}</Text>
                  <Text style={styles.commonText}>¥{MethodUtil.toThousands(discountAmount, 2) || 0}</Text>
                </View>
              </View>
              <View style={styles.section}>
                <View style={styles.commonLine}>
                  <Text style={styles.commonLabel}>不含税差异调整</Text>
                  <Text style={styles.commonLabel}>税额差异调整</Text>
                  <Text style={styles.commonLabel}>结算日期</Text>
                </View>
                <View style={styles.commonLine}>
                  <Text style={styles.commonText}>{diffNoTax || 0}</Text>
                  <Text style={styles.commonText}>{diffTaxAmount || 0}</Text>
                  <Text style={styles.commonText}>{(this.pageParams.companyType === 1 ? settleDate.substring(0, 10) : invocieDate.substring(0, 10)) || '-'}</Text>
                </View>
              </View>
              <View style={styles.section}>
                <View style={styles.commonLine}>
                  <Text style={styles.commonLabel}>备注</Text>
                  <Text style={styles.commonLabel}>审批意见</Text>
                  <Text style={styles.commonLabel}></Text>
                </View>
                <View style={styles.commonLine}>
                  <Text style={[styles.commonText, { color: style.color.themeColor, marginLeft: -6 * scale }]} onPress={() => { this.showRemark(0, (remark || '无')) }}>【查看备注】</Text>
                  <Text style={[styles.commonText, { color: style.color.themeColor, marginLeft: -6 * scale }]} onPress={() => { this.showRemark(1, (rejectsRemark || '无')) }}>【查看审批意见】</Text>
                  <Text style={styles.commonText}></Text>
                </View>
              </View>

              <View style={{ paddingLeft: 4 * scale, marginTop: 46 * scale, marginBottom: 14 * scale }}>
                <Text style={{ fontSize: 16 * scale }}>结算明细</Text>
              </View>

              {
                detailItemList && detailItemList.length ?
                  detailItemList.map((item, index) => {
                    const { goodsName, settleQuantity, settlePrice, diffNoTax, taxAmount, orderId,
                      putinDetailId, putoutId, settleAmount, bizStaffName, bizLineIdName, organName } = item || {};
                    return (
                      <View key={index} style={styles.detailItem}>
                        <Text style={styles.goodsName}>{goodsName || '-'}</Text>
                        <View style={styles.section}>
                          <View style={styles.commonLine}>
                            <Text style={styles.commonLabel}>结算量（吨）</Text>
                            <Text style={styles.commonLabel}>结算单价（元/吨）</Text>
                            <Text style={styles.commonLabel}>货款不含税（元）</Text>
                          </View>
                          <View style={styles.commonLine}>
                            <Text style={styles.commonText}>{settleQuantity || 0}</Text>
                            <Text style={styles.commonText}>{MethodUtil.toThousands(settlePrice, 2) || 0}</Text>
                            <Text style={styles.commonText}>{MethodUtil.toThousands(settleAmount, 2) || 0}</Text>
                          </View>
                        </View>
                        <View style={styles.section}>
                          <View style={styles.commonLine}>
                            <Text style={styles.commonLabel}>货款税额（元）</Text>
                            <Text style={styles.commonLabel}>不含税差异（元）</Text>
                            <Text style={styles.commonLabel}>税款差异（元）</Text>
                          </View>
                          <View style={styles.commonLine}>
                            <Text style={styles.commonText}>{MethodUtil.toThousands(taxAmount, 2) || 0}</Text>
                            <Text style={styles.commonText}>{MethodUtil.toThousands(diffNoTax, 2) || 0}</Text>
                            <Text style={styles.commonText}>{MethodUtil.toThousands(diffTaxAmount, 2) || 0}</Text>
                          </View>
                        </View>
                        <View style={styles.section}>
                          <View style={styles.commonLine}>
                            <Text style={styles.commonLabel}>订单号</Text>
                            <Text style={styles.commonLabel}>{this.pageParams.companyType === 1 ? '收货单子项号' : '发货单号'}</Text>
                            <Text style={styles.commonLabel}>业务员（部门）</Text>
                          </View>
                          <View style={styles.commonLine}>
                            <Text style={[styles.commonText, { color: style.color.themeColor }]} onPress={() => { this.props.navigation.navigate('OrderDetailsPage', { orderId, choice: this.pageParams.choice || {} }) }}>{orderId || '-'}</Text>
                            <Text style={styles.commonText}>{this.pageParams.companyType === 1 ? (putinDetailId || '-') : (putoutId || '-')}</Text>
                            <Text style={styles.commonText}>{bizStaffName || '--'} | {bizLineIdName || '--'} | {organName || '--'}</Text>
                          </View>
                        </View>
                      </View>

                    )
                  })
                  : <PageStatusIndex status={'empty'} />
              }

              {/* 一个结算单 可能有好几个发票 以下是结算单的发票列表 */}
              {
                invoiceInfoList && invoiceInfoList.length ? (<View style={{ backgroundColor: '#fff', borderRadius: 4 * scale, marginBottom: 20 * scale }}>
                  <View style={styles.billNumWrap}>
                    <Text style={styles.commonTitleAll}>发票信息</Text>
                  </View>
                  <View style={{ paddingVertical: 10 * scale }}>
                    {
                      invoiceInfoList.map((item, index) => {
                        let { invoiceNo, totalAmt } = item || {};
                        return (
                          <View key={index} style={styles.billInfoWrap}>
                            <View style={styles.itemRow}>
                              <Text style={styles.commonTitle}>发票号: </Text>
                              <TouchableOpacity style={{ flex: 1, flexDirection: 'row', paddingRight: 10 * scale }} activeOpacity={1} onPress={() => {
                                this.props.navigation.navigate('BillDetailPage', {
                                  title: this.pageParams.selectedName,
                                  companyType: this.pageParams.companyType,
                                  data: item,
                                  choice: this.pageParams.choice
                                })
                              }} >
                                <Text style={[styles.commonText, { color: style.color.themeColor }]}>{invoiceNo || '-'}</Text>
                              </TouchableOpacity>
                            </View>
                            <View style={[styles.itemRow, { width: '35%' }]}>
                              <Text style={[styles.commonTitle]}>金额: </Text>
                              <Text numberOfLines={1} style={[styles.commonText, { flex: 1 }]}>¥<Text style={{ fontSize: 13 * scale }} >{MethodUtil.toThousands(totalAmt, 2)}</Text></Text>
                            </View>
                          </View>
                        )
                      })
                    }
                  </View>
                </View>) : null
              }
            </ScrollView>
            : (<View style={{ position: 'absolute', height: GLOBAL.SCREEN_HEIGHT - 80, width: GLOBAL.SCREEN_WIDTH, top: 0 }}>
              <PageStatusIndex status={status} onErrorPress={() => { this.initPage() }} />
            </View>)
        }

        <CommonDialog modalVisible={modalVisible} title={modalTitle} text={alertRemark} onClosePress={() => { this.setState({ modalVisible: false }) }} />
      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: style.color.bgGray,
  },
  accountNum: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginTop: 20 * scale,
    marginBottom: 10 * scale,
    paddingLeft: 4 * scale,
  },
  section: {
    marginTop: 20 * scale,
    paddingLeft: 4 * scale
  },
  commonLine: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    marginBottom: 7 * scale
  },
  commonLabel: {
    flex: 1,
    opacity: .8,
    fontSize: 13 * scale,
  },
  commonText: {
    flex: 1,
    fontSize: 13 * scale,
  },
  detailItem: {
    borderRadius: 4 * scale,
    backgroundColor: '#fff',
    marginBottom: 20 * scale,
    paddingLeft: 10 * scale,
    paddingRight: 4 * scale,
    paddingTop: 16 * scale,
    paddingBottom: 16 * scale
  },
  goodsName: {
    fontWeight: 'bold',
    fontSize: 16 * scale,
  },
  billNumWrap: {
    borderStyle: 'solid',
    borderBottomColor: '#E3E7F0',
    borderBottomWidth: 1 * scale,
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 10 * scale,
    height: 36 * scale
  },
  billInfoWrap: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: 10 * scale,
    width: '100%',
    height: 40 * scale
  },
  commonTitle: {
    fontSize: 13 * scale,
  },
  itemRow: {
    flexDirection: 'row',
    alignItems: 'center',
    width: '65%',
  },
  commonTitleAll: {
    fontSize: 16 * scale
  }
})